package com.hualan.dao.shopdao.impl;

import com.hualan.bean.PanghuShop;
import com.hualan.dao.shopdao.ShopDao;
import com.hualan.utils.C3p0Util;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShopDaoImpl implements ShopDao {
	@Override
	public PanghuShop getPanghuShopById(int id) {
		String selectSql = "select shop_name from panghu_shop where shop_id = ?";
		Connection connection = C3p0Util.getConnection();
		PanghuShop panghuShop = C3p0Util.queryOne(selectSql,connection, PanghuShop.class, id);
		return panghuShop;
	}
	
	@Override
	public List<PanghuShop> getIdByName(String name) {
		String selectSql = "select shop_id from panghu_shop where shop_name like ?";
		return C3p0Util.query(selectSql,PanghuShop.class,"%"+name+"%");
	}
	
	@Override
	public HashMap<String, Object> getShops(Map<String, String> map) {
		List<Object> parameteres = new ArrayList<>();
		String sql = "select shop_id,shop_name,shop_phone,shop_address,shop_describe,sales_volume,shop_status from panghu_shop where 1 = 1";
		StringBuilder builder = new StringBuilder(sql);
		int pageNum = Integer.parseInt(map.get("pageNum"));
		int pageSize = Integer.parseInt(map.get("pageSize"));
		HashMap<String, Object> data = new HashMap<>();
		Long total;
		if (map.size() == 2){
			List<PanghuShop> query = C3p0Util.query(sql, PanghuShop.class);
			total = (long) query.size();
			builder.append(" limit ?,?");
			List<PanghuShop> query1 = C3p0Util.query(builder.toString(), PanghuShop.class, (pageNum - 1) * pageSize, pageSize);
		
			data.put("total",total);
			data.put("list",query1);
			return data;
		}
		
		if (map.containsKey("keyword")) {
			builder.append(" and shop_name like ?");
			parameteres.add("%"+map.get("keyword")+"%");
		}
		
		if (map.containsKey("phone")){
			builder.append(" and shop_phone like ?");
			parameteres.add("%"+map.get("phone")+"%");
		}
		
		if (map.containsKey("shopStatus")){
			builder.append(" and shop_status = ?");
			parameteres.add(map.get("shopStatus"));
		}
		
		List<Map<String, Object>> query = C3p0Util.query(builder.toString(), parameteres.toArray());
		
		total = (long) query.size();
		System.out.println(total);
		parameteres.add((pageNum - 1) * pageSize);
		parameteres.add(pageSize);
		builder.append(" limit ?,?");
		List<PanghuShop> query1 = C3p0Util.query(builder.toString(), PanghuShop.class, parameteres.toArray());
		data.put("total",total);
		data.put("list",query1);
		return data;
		
	}
	
	
}
